import React, { useState } from 'react';
import { createTopic } from '../api';
import { useNavigate } from 'react-router-dom';

interface TopicModalProps {
  visible: boolean;
  onClose: () => void;
}

const TopicModal: React.FC<TopicModalProps> = ({ visible, onClose }) => {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  if (!visible) return null;

  const handleSubmit = async () => {
    if (!name.trim()) {
      alert('请输入话题名称');
      return;
    }
    setLoading(true);
    try {
      const res = await createTopic({ name, description });
      const topicId = res.data?.data?.id || res.data?.id;
      setName('');
      setDescription('');
      onClose();
      if (topicId) navigate(`/topics/${topicId}`);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  return (
    <div style={{
      position: 'fixed', left: 0, top: 0, width: '100vw', height: '100vh', background: 'rgba(0,0,0,0.18)', zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center'
    }}>
      <div style={{ background: '#fff', borderRadius: 12, padding: 32, minWidth: 340, boxShadow: '0 2px 16px 0 rgba(0,0,0,0.13)' }}>
        <h2 style={{ marginTop: 0, marginBottom: 18, fontWeight: 700, fontSize: 22, textAlign: 'center' }}>创建话题</h2>
        <div style={{ marginBottom: 18 }}>
          <input
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="名称"
            maxLength={20}
            style={{ fontSize: 16, padding: '8px 10px', borderRadius: 6, border: '1px solid #ddd', width: '100%' }}
            onKeyDown={handleKeyDown}
            autoFocus
          />
        </div>
        <div style={{ marginBottom: 24 }}>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            placeholder="请输入话题描述 ..."
            maxLength={100}
            style={{ fontSize: 15, padding: '8px 10px', borderRadius: 6, border: '1px solid #ddd', width: '100%', minHeight: 60, resize: 'vertical' }}
            onKeyDown={handleKeyDown}
          />
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
          <button onClick={onClose} style={{ background: '#e5e7eb', color: '#222', borderRadius: 8, minWidth: 70 }}>取消</button>
          <button onClick={handleSubmit} disabled={loading} style={{ background: '#222', color: '#fff', borderRadius: 8, minWidth: 70, fontWeight: 600 }}>确定</button>
        </div>
      </div>
    </div>
  );
};

export default TopicModal;
